package com.bawei.module_live.version2.adapter

import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.ImageView
import androidx.media3.common.MediaItem
import androidx.media3.common.PlaybackException
import androidx.media3.common.Player
import androidx.media3.datasource.DefaultHttpDataSource
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
import androidx.media3.ui.PlayerView
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_live.R
import com.bawei.module_live.version2.mvi.model.entity.LiveEntity2
import androidx.media3.datasource.HttpDataSource
 import kotlinx.coroutines.launch
import java.util.Timer
import java.util.TimerTask
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import android.util.Log
import com.bawei.module_live.gift.GiftApi
import okhttp3.ResponseBody
import retrofit2.Retrofit
import com.opensource.svgaplayer.SVGAParser
import com.opensource.svgaplayer.SVGAVideoEntity
import com.opensource.svgaplayer.SVGACallback
import android.widget.Toast
import java.io.File
import java.net.URL
import com.bawei.module_live.adapter.GiftAdapter
import com.bawei.module_live.version1.GiftEntity
import com.google.android.material.bottomsheet.BottomSheetDialog
import androidx.recyclerview.widget.GridLayoutManager

import android.os.Handler
import android.os.Looper

class LiveRoomAdapter(
    private val liveRooms: ArrayList<LiveEntity2>,
    private val svgaImageView: com.opensource.svgaplayer.SVGAImageView
) : RecyclerView.Adapter<LiveRoomAdapter.LiveRoomViewHolder>() {

    // 保存每个ViewHolder的player
    private val playerMap = mutableMapOf<Int, ExoPlayer>()
    // 添加数据更新方法
    private var onlineCountMap = mutableMapOf<String, Int>()
    // 定义点击监听接口
    var onItemClickListener: ((viewId: Int, position: Int, item: LiveEntity2) -> Unit)? = null
    private val timers = mutableListOf<Timer>()

    fun setOnlineCount(roomId: String, count: Int) {
        onlineCountMap[roomId] = count
        notifyDataSetChanged()
    }

    fun updateData(newList: List<LiveEntity2>) {
        liveRooms.clear()
        liveRooms.addAll(newList)
        notifyDataSetChanged()
    }

    // 新增：显示红包的方法
    fun showRedEnvelope(position: Int) {
        val holder = getViewHolderAtPosition(position)
        holder?.let {
            it.redEnvelope.visibility = View.VISIBLE
            it.redEnvelopeTime.visibility = View.VISIBLE
            Log.d("RedEnvelope", "显示红包在位置: $position")
        }
    }

    // 新增：隐藏红包的方法
    fun hideRedEnvelope(position: Int) {
        val holder = getViewHolderAtPosition(position)
        holder?.let {
            it.redEnvelope.visibility = View.GONE
            it.redEnvelopeTime.visibility = View.GONE
            Log.d("RedEnvelope", "隐藏红包在位置: $position")
        }
    }

    // 新增：获取特定位置的ViewHolder
    private fun getViewHolderAtPosition(position: Int): LiveRoomViewHolder? {
        // 这里需要通过RecyclerView来获取ViewHolder
        // 由于Adapter无法直接访问RecyclerView，我们需要通过其他方式
        // 暂时返回null，实际使用时会通过Activity调用
        return null
    }

    // 新增：通过外部传入的ViewHolder来显示红包
    fun showRedEnvelopeForHolder(holder: LiveRoomViewHolder) {
        holder.redEnvelope.visibility = View.VISIBLE
        holder.redEnvelopeTime.visibility = View.VISIBLE
        Log.d("RedEnvelope", "显示红包")
    }

    // 新增：通过外部传入的ViewHolder来隐藏红包
    fun hideRedEnvelopeForHolder(holder: LiveRoomViewHolder) {
        holder.redEnvelope.visibility = View.GONE
        holder.redEnvelopeTime.visibility = View.GONE
        Log.d("RedEnvelope", "隐藏红包")
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LiveRoomViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_liveing, parent, false)
        return LiveRoomViewHolder(view)
    }

    // 只为当前可见item轮询在线人数
    private var currentPollingTimer: Timer? = null
    private var currentPollingRoomId: String? = null
    private var currentPollingHolder: LiveRoomViewHolder? = null

    // Handler和倒计时Runnable管理
    private val handler = Handler(Looper.getMainLooper())
    private val countdownRunnables = mutableMapOf<LiveRoomViewHolder, Runnable>()

    // 提供外部调用，通知当前可见item变化（只传holder）
    fun onCurrentItemChanged(holder: LiveRoomViewHolder) {
        // 先移除旧的
        countdownRunnables[holder]?.let { handler.removeCallbacks(it) }
        var countdown = 10
        val runnable = object : Runnable {
            override fun run() {
                if (countdown > 0) {
                    holder.redEnvelopeTime.text = String.format("%02d:%02d", countdown / 60, countdown % 60)
                    countdown--
                    handler.postDelayed(this, 1000)
                } else {
                    hideRedEnvelopeForHolder(holder)
                    countdownRunnables.remove(holder)
                }
            }
        }
        countdownRunnables[holder] = runnable
        handler.post(runnable)
    }

    fun releaseAllRunnables() {
        countdownRunnables.values.forEach { handler.removeCallbacks(it) }
        countdownRunnables.clear()
    }

    override fun onBindViewHolder(holder: LiveRoomViewHolder, position: Int) {
        val liveRoom = liveRooms[position]
        holder.playerView.player?.release()
        holder.playerView.player = null
        playerMap.remove(position)

        // 判断 play_url 是否有效
        if (liveRoom.play_url.isNullOrEmpty() || !liveRoom.play_url.startsWith("http")) {
            holder.tvNoData.visibility = View.VISIBLE
            holder.playerView.visibility = View.GONE
            holder.tvNoData.text = "暂无直播"
            return
        } else {
            holder.tvNoData.visibility = View.GONE
            holder.playerView.visibility = View.VISIBLE
        }

        val player = ExoPlayer.Builder(holder.itemView.context).build()
        val mediaItem = MediaItem.fromUri(liveRoom.play_url)
        player.setMediaItem(mediaItem)
        player.prepare()
        player.play()
        holder.playerView.player = player
        playerMap[position] = player

        player.addListener(object : Player.Listener {
            override fun onPlayerError(error: PlaybackException) {
                holder.tvNoData.visibility = View.VISIBLE
                holder.playerView.visibility = View.GONE
                holder.tvNoData.text = "直播间不存在或已关闭"
            }
        })
        // 显示在线人数
        val count = onlineCountMap[liveRoom.room_id] ?: 0
        holder.audienceNum.text = count.toString()
        // 不再为每个item轮询，只在外部通知时轮询当前item

        // 设置控件点击监听
        holder.redEnvelope.setOnClickListener {
            onItemClickListener?.invoke(R.id.red_envelope, position, liveRoom)
        }

        // 小红心动画
        holder.fav.setOnClickListener {
            holder.klv.addLikeImages(
                R.drawable.fav_0,
                R.drawable.fav_1,
                R.drawable.fav_2,
                R.drawable.fav_3,
                R.drawable.fav_4,
                R.drawable.fav_5
            )
            holder.klv.addFavor()
            // 可选：点赞数本地+1
            // holder.audienceNum.text = (holder.audienceNum.text.toString().toInt() + 1).toString()
        }

        // 礼物弹窗和动画
        holder.gift.setOnClickListener {
            kotlinx.coroutines.GlobalScope.launch(kotlinx.coroutines.Dispatchers.Main) {
                try {
                    // 1. 获取礼物列表（用全局 RetrofitFactory）
                    val apiList = com.bawei.lib_net.RetrofitFactory.getRetrofitFactory().create(com.bawei.module_live.version1.GiftApi::class.java)
                    val response = apiList.getGiftList()
                    if (response.code == 200 && response.data.isNotEmpty()) {
                        // 2. 弹出礼物选择弹窗
                        val dialog = BottomSheetDialog(holder.itemView.context)
                        val view = LayoutInflater.from(holder.itemView.context).inflate(com.bawei.module_live.R.layout.dialog_gift_list, null)
                        val rv = view.findViewById<androidx.recyclerview.widget.RecyclerView>(com.bawei.module_live.R.id.rv_gift)
                        rv.layoutManager = GridLayoutManager(holder.itemView.context, 4)
                        rv.adapter = GiftAdapter(response.data) { gift ->
                            // 3. 点击item时下载并播放动画（用全局 RetrofitFactory）
                            kotlinx.coroutines.GlobalScope.launch(kotlinx.coroutines.Dispatchers.Main) {
                                try {
                                    val filename = gift.svgaPath.removeSuffix(".svga")
                                    val api = com.bawei.lib_net.RetrofitFactory.getRetrofitFactory().create(com.bawei.module_live.gift.GiftApi::class.java)
                                    val responseBody = api.downloadSvga(filename)
                                    val file = java.io.File(holder.itemView.context.cacheDir, "$filename.svga")
                                    file.outputStream().use { output ->
                                        responseBody.byteStream().copyTo(output)
                                    }
                                    svgaImageView.stopAnimation(true)
                                    svgaImageView.setVideoItem(null)
                                    svgaImageView.visibility = View.VISIBLE
                                    val parser = com.opensource.svgaplayer.SVGAParser(holder.itemView.context)
                                    parser.decodeFromInputStream(file.inputStream(), file.name, object : com.opensource.svgaplayer.SVGAParser.ParseCompletion {
                                        override fun onComplete(videoItem: com.opensource.svgaplayer.SVGAVideoEntity) {
                                            svgaImageView.setVideoItem(videoItem)
                                            svgaImageView.loops = 1
                                            svgaImageView.startAnimation()
                                            svgaImageView.callback = object : com.opensource.svgaplayer.SVGACallback {
                                                override fun onFinished() {
                                                    svgaImageView.visibility = View.GONE
                                                    svgaImageView.setVideoItem(null)
                                                }
                                                override fun onPause() {}
                                                override fun onRepeat() {}
                                                override fun onStep(frame: Int, percentage: Double) {}
                                            }
                                        }
                                        override fun onError() {
                                            Toast.makeText(holder.itemView.context, "动画解析失败", Toast.LENGTH_SHORT).show()
                                            svgaImageView.visibility = View.GONE
                                            svgaImageView.setVideoItem(null)
                                        }
                                    }, true)
                                } catch (e: Exception) {
                                    android.util.Log.e("GiftDebug", "动画加载失败", e)
                                    Toast.makeText(holder.itemView.context, "动画加载失败", Toast.LENGTH_SHORT).show()
                                }
                            }
                            dialog.dismiss()
                        }
                        dialog.setContentView(view)
                        dialog.show()
                    } else {
                        Toast.makeText(holder.itemView.context, "获取礼物失败", Toast.LENGTH_SHORT).show()
                    }
                } catch (e: Exception) {
                    android.util.Log.e("GiftDebug", "网络异常", e)
                    Toast.makeText(holder.itemView.context, "网络异常", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    override fun onViewRecycled(holder: LiveRoomViewHolder) {
        holder.playerView.player?.release()
        holder.playerView.player = null
        playerMap.remove(holder.bindingAdapterPosition)
        // 停止倒计时
        countdownRunnables[holder]?.let { handler.removeCallbacks(it) }
        countdownRunnables.remove(holder)
        // 如果当前回收的是正在轮询的holder，停止轮询
        if (holder == currentPollingHolder) {
            currentPollingTimer?.cancel()
            currentPollingTimer = null
            currentPollingHolder = null
            currentPollingRoomId = null
        }
        holder.audienceNum.text = ""
        super.onViewRecycled(holder)
    }

    override fun getItemCount(): Int = liveRooms.size

    fun releaseAllPlayers() {
        playerMap.values.forEach { it.release() }
        playerMap.clear()
    }

    inner class LiveRoomViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val playerView: PlayerView = itemView.findViewById(R.id.player_view)
        val tvNoData: TextView = itemView.findViewById(R.id.tv_no_data)
        val audienceNum: TextView = itemView.findViewById(R.id.audience_num)
        val redEnvelope: ImageView = itemView.findViewById(R.id.red_envelope)
        val redEnvelopeTime: TextView = itemView.findViewById(R.id.red_envelope_time)
        // 新增
        val klv: com.kaisengao.likeview.like.KsgLikeView = itemView.findViewById(R.id.klv)
        // 移除 item 的 svgaImageView
        val gift: ImageView = itemView.findViewById(R.id.gift)
        val fav: ImageView = itemView.findViewById(R.id.live_detail_fav)
        var timer: Timer? = null
    }
}